package cn.maihe.elg.operation.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: Alan
 */
public class SPDBUtil {
    //发送交易参数
    private static String sendType = "http";//通讯协议
    private static String host = "120.24.92.203";//目标地址，bisafe所在地址
    private static int port = 8001;//目标端口，bisafe nchttp服务监听端口
    /**
     * @param [xmlString] 报文长度6位（不足左补0）+报文（报文头+报文体）
     * @return java.lang.String
     * @describe HTTP协议发送交易
     * @date 2019/12/6
     */
    public static String sendByHttp(String xmlString, String sendType, String host, int port) throws UnsupportedEncodingException {

//        System.out.println("the protocol is :" + sendType);
//        System.out.println("the data send to host is :" + xmlString);

        InputStream in = null;
        byte[] rcv = null;
        byte[] sendByte = xmlString.getBytes();
        String urlStr = "http://" + host + ":" + port + "/";
//        System.out.println("the url is :" + urlStr);
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection;
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.getOutputStream().write(sendByte);
            connection.getOutputStream().flush();
            in = connection.getInputStream();
            //读取返回的前6个字节，获得报文总长度
            byte[] lengthdata = new byte[6];
            int i = in.read(lengthdata);
            String lengthstr = (new String(lengthdata)).trim();
            int length = Integer.parseInt(lengthstr);
            //根据报文总长度读取后续报文
            rcv = new byte[length];
            int j = 0;
            byte[] rcvtmp = new byte[10240];
            int srcindex = 0;
            while (j >= 0) {
                j = in.read(rcvtmp);
                if (j < 0)
                    break;
                System.arraycopy(rcvtmp, 0, rcv, srcindex, j);
                srcindex = srcindex + j;
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(rcv, "GBK");
    }

    /**
     * @param [content, contentType, url]
     * @return java.io.InputStream
     * @describe 签名验签公共发送报文类
     * @date 2019/12/6
     */
    public static InputStream send(byte[] content, String contentType, String url) throws IOException {
        URL urll = new URL(url);
        HttpURLConnection con1 = (HttpURLConnection) urll.openConnection();//配置报文头
        con1.setDoInput(true);
        con1.setDoOutput(true);
        con1.setRequestMethod("POST");
        con1.setRequestProperty("Content-Type", contentType);
        con1.setRequestProperty("Content-Length", String.valueOf(content.length));
        con1.connect();
        con1.getOutputStream().write(content);
        con1.getOutputStream().flush();
//        System.out.println(con1.getResponseCode());
//        System.out.println(con1.getResponseMessage());
        InputStream in = con1.getInputStream();
        return in;
    }


    public static String parseSignContent(InputStream in) {
        try {
            Element el = parse(in);
            String result = el.element("head").element("result").getTextTrim();
            if (result.equals("0"))
                return el.element("body").element("sign").getText();
            else
                return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Map parseVerifyContent(InputStream in) {
        Map context = new HashMap();
        try {
            Element el = parse(in);
            String result = el.element("head").element("result").getTextTrim();
            if (result.equals("0")) {
                String content =
                        el.element("body").element("sic").element("body").asXML();
                String DN = el.element("body").element("certdn").getText();
                context.put("plain", content);
                context.put("dn", DN);
                return context;
            } else
                return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static Element parse(InputStream io) throws DocumentException, UnsupportedEncodingException {
        SAXReader reader = new SAXReader();
        reader.setValidation(false);
        InputStreamReader bi = new InputStreamReader(io, "GBK");
        Document doc = null;
        doc = reader.read(bi);
        return doc.getRootElement();
    }
}
